<template>
  <div class="detail-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-width="100px"
      label-suffix=":"
    >

      <sticky :z-index="10" :class-name="'sub-navbar ' + postForm.color">
        <el-button v-loading="loading" type="info" @click="$router.back()">
          返回
        </el-button>
        <el-button v-loading="loading" type="success" @click="submitForm">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </sticky>

      <div class="app-container" style="padding: 10px 20px 50px 10px">

        <el-link v-if="product.skuName.length === 0" type="primary" @click="$router.push(`/product/edit/${productId}`)">还没设置规格, 去添加</el-link>

        <template v-else>
          <el-row>
            <h1>{{ product.title }}</h1>
            <el-col :span="24" v-if="false">
              <el-form-item label="价格" style="width: 350px">
                <el-input v-model="product.title" disabled />
              </el-form-item>
              <el-form-item label="库存" style="width: 350px">
                <el-input v-model="product.stock" disabled />
              </el-form-item>
              <el-form-item label="成本" style="width: 350px">
                <el-input v-model="product.price_cost" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider v-if="false" />
          <el-row>
            <el-col :span="4">
              <el-form-item label="请选择规格"></el-form-item>
            </el-col>
          </el-row>
          <el-row v-for="(item, index) in product.skuName" :key="index">
            <el-col :span="4" style="text-align: right; margin-bottom: 10px; padding-right: 20px">
              <el-tag
                style="font-weight: 700; cursor: pointer"
                :closable="item.checked"
                @click="handleCheckedAll(item)"
                @close="handleCloseAll(item)"
              >{{ item.name }}</el-tag>
            </el-col>
            <el-col :span="20">
              <template v-for="(o, i) in item.values">
                <el-tag
                  :key="i"
                  :type="!o.checked ? 'info': 'danger'"
                  style="margin-right: 10px; cursor: pointer; margin-bottom: 10px"
                  :closable="o.checked"
                  @click="handleChecked(o, item)"
                  @close="handleClose(o, item)"
                  v-if="o.value"
                >
                  {{ o.value }}
                </el-tag>
              </template>
            </el-col>
          </el-row>
          <br />
          <br />
          <el-row>
            <el-col :span="24">
              <el-form-item label="图片" prop="image">
                <upload-image
                  bucket="product-sku"
                  :max="1"
                  :width="750"
                  :height="750"
                  :quality="50"
                  @onSuccess="onSuccess"
                  @onRemove="onRemove"
                  :file-list="postForm.image"
                />
              </el-form-item>
              <el-form-item label="成本" prop="self_cost" style="width: 350px" required>
                <el-input v-model.trim="postForm.self_cost" />
              </el-form-item>
              <el-form-item label="价格" prop="price" style="width: 350px" required>
                <el-input v-model.trim="postForm.price" />
              </el-form-item>
              <el-form-item label="库存" prop="stock" style="width: 350px" required>
                <el-input v-model.trim="postForm.stock" />
              </el-form-item>
              <el-form-item label="排序" prop="sort" style="width: 200px">
                <el-input v-model.number="postForm.sort" />
                <span>-128 ~ 127</span>
              </el-form-item>
              <el-form-item label="状态" style="width: 200px">
                <el-switch v-model="postForm.status" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </div>

    </el-form>
  </div>
</template>

<script>
import api from '@/api'
import Sticky from '@/components/Sticky'
import UploadImage from '@/components/Upload/UploadImage'
export default {
  name: 'SkuDetail',
  components: {
    Sticky,
    UploadImage
  },
  props: {
    /**
     * 是否为编辑
     */
    isEdit: {
      type: Boolean,
      default: false
    },
    productId: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      id: -1,
      loading: false,
      postForm: {
        color: 'draft',
        status: true,
        sort: 0,
        image: []
      },
      product: {
        skuName: []
      },
      rules: {
      }
    }
  },
  created() {
    this.fetchProduct().then(() => {
      if (this.isEdit) {
        this.id = (this.$route.params && this.$route.params.id) || -1
        this.fetchData(this.id)
      }
    })
  },
  methods: {
    // 选择与取消
    handleChecked(o, item) {
      this.$set(o, 'checked', true)
      const num = item.values.filter(x => x.value).length
      const checkNum = item.values.filter(x => x.checked).length
      if (num === checkNum) {
        this.$set(item, 'checked', true)
      }
    },
    handleClose(o, item) {
      this.$set(o, 'checked', false)
      this.$set(item, 'checked', false)
    },
    handleCheckedAll(item) {
      this.$set(item, 'checked', true)
      item.values.forEach(x => {
        this.$set(x, 'checked', true)
      })
    },
    handleCloseAll(item) {
      this.$set(item, 'checked', false)
      item.values.forEach(x => {
        this.$set(x, 'checked', false)
      })
    },
    async fetchProduct() {
      const response = await api.sku.viewProduct({ product_id: this.productId })
      this.product = Object.assign({}, response.data)
      this.$set(this.postForm, 'self_cost', this.product.price_cost)
      this.$set(this.postForm, 'price', this.product.price)
      this.$set(this.postForm, 'stock', this.product.stock)
    },
    /**
     * 获取编辑数据
     */
    async fetchData(id) {
      const response = await api.sku.view({ id })
      this.postForm = Object.assign({}, response.data)
      // 状态
      this.postForm.status = +this.postForm.status === 1
      // 图片
      if (this.postForm.image) {
        this.postForm.image = [{
          id: +this.postForm.image.id,
          url: this.postForm.image.thumbnail_path
        }]
      } else {
        this.postForm.image = []
      }
      // sku
      if (this.postForm.sku_list) {
        const list = this.postForm.sku_list.split('|')
        this.product.skuName.forEach(x => {
          x.values.forEach(y => {
            if (list.indexOf(y.id) > -1) {
              this.$set(y, 'checked', true)
            }
          })
        })
      }
    },
    /**
     * 提交表单
     */
    submitForm() {
      // 判断选中没有
      const sku = []
      this.product.skuName.forEach(x => {
        x.values.forEach(y => {
          if (y.checked) {
            sku.push(y.id)
          }
        })
      })
      if (sku.length === 0) {
        return this.$notify({
          title: '操作错误',
          message: '请选择规格',
          type: 'error',
          duration: 2000
        })
      }
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 状态
          const status = this.postForm.status ? 1 : 0
          // 图片
          let image = 0
          if (this.postForm.image && this.postForm.image.length > 0) {
            image = this.postForm.image.map(x => x.id)[0]
          }
          api.sku.edit({
            id: this.id,
            ...this.postForm,
            status,
            image_id: image,
            product_id: this.productId,
            // sku_list: JSON.stringify(sku)
            sku_list: sku.join('|')
          }).then(response => {
            this.loading = false
            this.$notify({
              title: '成功',
              message: response.message || '操作成功',
              type: 'success',
              duration: 2000
            })
            this.$router.push(`/product/sku-list/${this.productId}`)
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    /**
     * 图片上传
     */
    onSuccess(data, fileList) {
      if (data && data.id) {
        this.postForm.image.push({
          id: data.id,
          url: data.thumbnail
        })
      }
    },
    /**
     * 删除图片
     */
    onRemove(data, fileList) {
      if (data && data.id) {
        this.postForm.image = this.postForm.image.filter(x => x.id !== data.id)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.detail-container {
  //
}
</style>
